package com.xw.comm.service.impl;

import com.xw.comm.service.SerialPortService;
import gnu.io.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.TooManyListenersException;

/**
 * @author xiongwei_vendor
 * @date 2020/12/8 19:28
 */
@Slf4j
@Service
public class SerialPortServiceImpl implements SerialPortService {

    private SerialPort serialPort;

    @Override
    public void start(String com) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, TooManyListenersException {
        log.info("com = {}", com);
        //打开串口
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(com.toUpperCase());
        //2000是打开超时时间
        CommPort commPort = portIdentifier.open(com, 2000);
        serialPort = (SerialPort) commPort;
        //设置参数（包括波特率，输入/输出流控制，数据位数，停止位和齐偶校验）
        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        //监听串口事件
        //Abc是实现SerialPortEventListener接口的类，具体读操作在里面进行
        serialPort.addEventListener(new SerialListener(serialPort));
        // 设置当有数据到达时唤醒监听接收线程
        serialPort.notifyOnDataAvailable(true);
        // 设置当通信中断时唤醒中断线程
        serialPort.notifyOnBreakInterrupt(true);
        //  in.close(); //关闭串口
    }

    @Override
    public void stop(String com) {
        serialPort.close();
    }

    @Override
    public boolean sendMessage(byte[] data) {
        if (serialPort == null) {
            return false;
        }
        try {
            OutputStream out = serialPort.getOutputStream();
            out.write(data);
            out.close();
            return true;
        } catch (IOException ioException) {
            log.error("ioException", ioException);
        }
        return false;
    }

    @Override
    public SerialPort getSerialPort() {
        return serialPort;
    }

}
